<?php
/**
 * knowledge.php
 * User: yzm
 * Date: 2017/7/25
 */

class Knowledge extends WebBase{

    /*
     * 知识库首页
     */
    public function index() {
        global $_W,$_GPC;

        //所有标签--用于筛选
        $label_list = pdo_getall('wherein_knowledge_label', array('uniacid' => $_W['uniacid']), array('label_id', 'label_name'));

        //二级分类
        if (!isset($_GPC['cat_id']) || $_GPC['cat_id'] == 0) {
            $category_child_list = pdo_fetchall("SELECT cat_id, cat_name FROM " . tablename('wherein_knowledge_category') . " WHERE `uniacid`=:uniacid AND `parent_id` <> 0", array(':uniacid' => $_W['uniacid']));
        } else {
            $category_child_list = pdo_getall('wherein_knowledge_category', array('uniacid' => $_W['uniacid'], 'parent_id' => $_GPC['cat_id']), array('cat_id', 'cat_name', 'sort_order'), '', array('sort_order DESC'));
        }

        if ($_W['isajax']) {
            $where_sql = ' WHERE `uniacid`=:uniacid ';
            $where[':uniacid'] = $_W['uniacid'];
            //符合问题的id集合
            $question_ids = array();

            /* 一级分类: 判断当前分类下是否有二级分类, 查询相关问题: 条件 一级分类+二级分类(如果有) */
            if (!empty($_GPC['cat_id']) && !isset($_GPC['cat_ids'])) {
                //查询当下有没有子分类
                $child_list = pdo_getall('wherein_knowledge_category', array('uniacid' => $_W['uniacid'], 'parent_id' => $_GPC['cat_id']), array('cat_id'));
                $child_list = empty($child_list) ? array() : return_array_value($child_list, 'cat_id');
                array_push($child_list, $_GPC['cat_id']);
                $child_list_implode = implode(',', $child_list);
                //查询问题id
                $question_list = pdo_fetchall("SELECT question_id FROM " . tablename('wherein_knowledge_question') . " WHERE `uniacid` = :uniacid AND `cat_id` IN (".$child_list_implode.")", array(':uniacid' => $_W['uniacid']));
                if (!empty($question_list)) {
                    $question_list = return_array_value($question_list, 'question_id');
                    foreach ($question_list as $v) {
                        array_push($question_ids, $v);
                    }
                    unset($question_list);//销毁
                } else {
                    array_push($question_ids, '0');
                }
            }

            /* 搜索-二级分类 */
            if (!empty($_GPC['cat_ids'])) {
                $need_list = array();
                $cat_ids = implode(',', $_GPC['cat_ids']);
                $question_list = pdo_fetchall("SELECT `question_id` FROM " . tablename('wherein_knowledge_question') . " WHERE `uniacid` = :uniacid AND `cat_id` IN (" . $cat_ids . ")", array(':uniacid' => $_W['uniacid']));
                if (!empty($question_list)) {
                    $question_list = return_array_value($question_list, 'question_id');
                    /* 搜索-标签 */
                    if (!empty($_GPC['label_ids'])) {
                        $label_ids = implode(',', $_GPC['label_ids']);
                        $label_question_list = pdo_fetchall("SELECT DISTINCT(`question_id`) FROM " . tablename('wherein_knowledge_relation') . " WHERE `uniacid` = :uniacid AND `label_id` IN (" . $label_ids . ")", array(':uniacid' => $_W['uniacid']));
                        $label_question_list = return_array_value($label_question_list, 'question_id');
                        $diff_list = array_intersect($question_list, $label_question_list);
                        if (!empty($diff_list)) {
                            $need_list = $diff_list;
                        }
                    } else {
                        $need_list = $question_list;
                    }
                }
                if (!empty($need_list)) {
                    foreach ($need_list as $v) {
                        array_push($question_ids, $v);
                    }
                } else {
                    array_push($question_ids, 0);
                }
            }

            /* 搜索-标签 */
            if (empty($_GPC['cat_ids']) && !empty($_GPC['label_ids'])) {
                $label_ids = implode(',', $_GPC['label_ids']);
                $question_list = pdo_fetchall("SELECT DISTINCT(`question_id`) FROM " . tablename('wherein_knowledge_relation') . " WHERE `uniacid` = :uniacid AND `label_id` IN (" . $label_ids . ")", array(':uniacid' => $_W['uniacid']));
                if (!empty($question_list)) {
                    $question_list = return_array_value($question_list, 'question_id');
                    foreach ($question_list as $v) {
                        array_push($question_ids, $v);
                    }
                } else {
                    array_push($question_ids, '0');
                }
            }

            /* 搜索-问题 */
            if (!empty($_GPC['question'])) {
                //模糊查询
                $where_sql .= " AND (`question` LIKE :question OR `similar_question` LIKE :similar_question)";
                $where[':question'] = '%' . $_GPC['question'] . '%';
                $where[':similar_question'] = '%' . $_GPC['question'] . '%';
            }

            if (!empty($question_ids)) {
                $question_ids = array_unique($question_ids);
                $where_sql .= ' AND `question_id` IN (' . implode(',', $question_ids) . ')';
            }

            $total = pdo_fetchcolumn("SELECT COUNT(*) FROM " . tablename('wherein_knowledge_question') . $where_sql, $where);

            $list = pdo_fetchall("SELECT * FROM ".tablename('wherein_knowledge_question') . $where_sql . " ORDER BY " . $_GPC['sortName'] . " " . $_GPC['sortOrder'] . " LIMIT " . $_GPC['offset'] . ", " . $_GPC['limit'], $where);
            if (!empty($list)) {
                foreach ($list as $key => $value) {
                    //一级--二级
                    $cate_data = pdo_get('wherein_knowledge_category', array('uniacid' => $_W['uniacid'], 'cat_id' => $value['cat_id']), array('parent_id', 'cat_name'));
                    if (!empty($cate_data['parent_id'])) {
                        $cate_ = pdo_getcolumn('wherein_knowledge_category', array('uniacid' => $_W['uniacid'], 'cat_id' => $cate_data['parent_id']), 'cat_name');
                        $cate_data['cat_name'] = $cate_ . '－－' . $cate_data['cat_name'];
                    }
                    $list[$key]['cat_name'] = $cate_data['cat_name'];
                    $label_name_list = pdo_fetchall("SELECT l.label_name FROM " . tablename('wherein_knowledge_label') . " AS l LEFT JOIN " . tablename('wherein_knowledge_relation') . " AS r ON r.label_id = l.label_id WHERE l.uniacid = :uniacid AND r.question_id = :question_id", array(':uniacid' => $_W['uniacid'], ':question_id' => $value['question_id']));
                    if (!empty($label_name_list)) {
                        $label_name_list = return_array_value($label_name_list, 'label_name');
                        $label_name_list = implode('、', $label_name_list);
                    } else {
                        $label_name_list = '无';
                    }

                    $list[$key]['label_name'] = $label_name_list;
                    $list[$key]['answer_all'] = htmlspecialchars_decode($value['answer']);
                    $list[$key]['answer'] = strip_tags(htmlspecialchars_decode($value['answer']));
                    $list[$key]['index'] = ($key+1) + ($_GPC['limit'] * ($_GPC['offset']/$_GPC['limit']));
                }
            }

            $out['total'] = $total;
            $out['rows'] = $list;
            $this->outjson($out);
        }

        include $this->template('index');
    }

    /*
     * 添加分类
     */
    public function addCate() {
        global $_W,$_GPC;
        /*
         * 需要参数
         * cat_id 分类id 如果是添加一级分类则为空
         * cat_name 分类名
         */

        if ($_W['isajax']) {
            //检测分类是否为空
            $cat_name = str_replace(" ", '', $_GPC['cat_name']);
            if (empty($cat_name)) {
                $this->outjson(array('code' => 100, 'msg' => '分类名不能为空'));
            }
            //检测该分类是否存在
            $res = $this->checkCateName($_GPC['cat_name'], !empty($_GPC['cat_id']) ? 1 : 0);
            if ($res['code'] == 0) {
                $this->outjson(array('code' => 206, 'msg' => '该分类已经存在'));
            }

            $data = array(
                'uniacid' => $_W['uniacid'],
                'parent_id' => !empty($_GPC['cat_id']) ? $_GPC['cat_id'] : 0,
                'cat_name' => trim($_GPC['cat_name']),
                'add_time' => $_W['timestamp']
            );

            if (pdo_insert('wherein_knowledge_category', $data)) {
                $insert_id = pdo_insertid();
                pdo_update('wherein_knowledge_category', array('sort_order' => $insert_id), array('cat_id' => $insert_id));
                $out['code'] = 200;
                $out['msg'] = '添加分类成功';
            } else {
                $out['code'] = 304;
                $out['msg'] = '添加分类失败';
            }
            $this->outjson($out);
        }
    }

    /*
     * 编辑分类
     */
    public function editCate() {
        global $_W,$_GPC;

        if ($_W['isajax']) {
            //检测分类是否为空
            if (empty($_GPC['cat_name'])) {
                $this->outjson(array('code' => 100, 'msg' => '分类名不能为空'));
            }
            //检测分类是否已经存在
            $is_parent = pdo_getcolumn('wherein_knowledge_category', array('uniacid' => $_W['uniacid'], 'cat_id' => $_GPC['cat_id']), 'parent_id');

            $res = $this->checkCateName($_GPC['cat_name'], $is_parent == 0 ? 0 : 1);
            if ($res['code'] == 0) {
                $out['code'] = 206;
                $out['msg'] = '该分类已经存在';
                $this->outjson($out);
            }
            $data = array(
                'cat_name' => trim($_GPC['cat_name'])
            );
            if (pdo_update('wherein_knowledge_category', $data, array('uniacid' => $_W['uniacid'], 'cat_id' => $_GPC['cat_id']))) {
                $out['code'] = 200;
                $out['msg'] = '修改分类成功';
            } else {
                $out['code'] = 304;
                $out['msg'] = '修改分类失败';
            }
            $this->outjson($out);
        }
    }

    /*
     * 删除分类
     */
    public function delCate() {
        global $_W,$_GPC;

        //判断是否为一级分类
        $get_cate = pdo_get('wherein_knowledge_category', array('uniacid' => $_W['uniacid'], 'cat_id' => $_GPC['cat_id']), array('cat_id', 'parent_id'));
        //判断数据真伪
        if (empty($get_cate)) {
            $out['code'] = 404;
            $out['msg'] = '没有找到要删除的数据';
            $this->outjson($out);
        }

        //查询是否存在相关问题
        $question_list = pdo_getall('wherein_knowledge_question', array('uniacid' => $_W['uniacid'], 'cat_id' => $_GPC['cat_id']), array('question_id'));
        //查询是否存在子分类
        $child_list = pdo_getall('wherein_knowledge_category', array('uniacid' => $_W['uniacid'], 'parent_id' => $_GPC['cat_id']));
        if (!empty($question_list) || !empty($child_list)) {
            $out['code'] = 412;
            $out['msg'] = '该分类下存在子分类或者相关问题,无法删除';
            $this->outjson($out);
        }
        if (pdo_delete('wherein_knowledge_category', array('cat_id' => $_GPC['cat_id']))) {
            $out['code'] = 200;
            $out['msg'] = '删除分类成功';
        } else {
            $out['code'] = 400;
            $out['msg'] = '删除分类失败';
        }
        $this->outjson($out);
    }

    /*
     * 分类排序
     * 需要 当前分类id 和分类sort_order
     */
    public function sortCate() {
        global $_W,$_GPC;
        //查询当前点击的下一条记录,然后交换sort_order

        $cat_data = pdo_get('wherein_knowledge_category', array('uniacid' => $_W['uniacid'], 'cat_id' => $_GPC['cat_id']), array('cat_id', 'parent_id'));
        if (empty($cat_data)) {
            $this->outjson(array('code' => 404, 'msg' => '查无此数据'));
        }

        /* 向上移动,查询比当前大一位的;向下移动,查询比当前小一位的 */
        $sort = $_GPC['type'] == 'up' ? ' > ': ' < ';
        $order = $_GPC['type'] == 'up' ? 'ASC' : 'DESC';

        //查询下一位的数据
        $get_sort_data = pdo_fetch("SELECT cat_id,sort_order FROM " . tablename('wherein_knowledge_category') . " WHERE `uniacid`=:uniacid AND `sort_order` " . $sort . " :sort_order AND `parent_id` = :parent_id ORDER BY `sort_order` " . $order . " LIMIT 1", array(':uniacid' => $_W['uniacid'], ':sort_order' => $_GPC['sort_order'], ':parent_id' => $cat_data['parent_id']));

        if (pdo_update('wherein_knowledge_category', array('sort_order' => $_GPC['sort_order']), array('uniacid' => $_W['uniacid'],'cat_id' => $get_sort_data['cat_id'])) && pdo_update('wherein_knowledge_category', array('sort_order' => $get_sort_data['sort_order']), array('uniacid' => $_W['uniacid'], 'cat_id' => $_GPC['cat_id']))) {
            $out['code'] = 200;
            $out['msg'] = '更新排序成功';
        } else {
            $out['code'] = 304;
            $msg = $_GPC['type'] == 'up' ? '该分类已在最高位置': '该分类已在最低位置';
            $out['msg'] = $msg;
        }
        $this->outjson($out);
    }

    /*
     * 处理问题-添加/编辑
     */
    public function operate() {
        global $_W,$_GPC;
        load()->func('tpl');

        if (!is_writable(ATTACHMENT_ROOT)) {
            message(ATTACHMENT_ROOT . '目录不可写, 请授权', $this->createWebUrl('knowledge', array('act' => 'index')), 'error');
        }
        //检测是upload和PHPExcel文件夹是否存在
        if (!is_dir(UPLOAD_ANSWER)) {
            if (!mkdir(UPLOAD_ANSWER, 0777, true)) {
                message('创建目录失败', 'referer', 'error');
            }
        }

        //所有分类
        $category_list = array();
        $category_list = pdo_getall('wherein_knowledge_category', array('uniacid' => $_W['uniacid'], 'parent_id' => '0'), array('cat_id', 'cat_name'), '', array('sort_order DESC'));
        foreach ($category_list as $k => $v) {
            $child_list = pdo_getall('wherein_knowledge_category', array('uniacid' => $_W['uniacid'], 'parent_id' => $v['cat_id']), array('cat_id', 'cat_name', 'sort_order'), '', array('sort_order DESC'));
            $category_list[$k] = array(
                'cat_id' => $v['cat_id'],
                'cat_name' => $v['cat_name'],
                'child_list' => $child_list
            );
            unset($child_list);
        }
        //所有标签
        $label_list = pdo_getall('wherein_knowledge_label', array('uniacid' => $_W['uniacid']), array('label_id', 'label_name'));

        /* 修改页面的数据处理 */
        if (!empty($_GPC['question_id'])) {

            $question_item = pdo_get('wherein_knowledge_question', array('question_id' => $_GPC['question_id']));
            $question_item['similar_question'] = !empty($question_item['similar_question']) ? explode(QUESTION_IMPLODE, $question_item['similar_question']) : array();

            $selected_label_list = pdo_fetchall("SELECT l.label_id,l.label_name FROM " . tablename('wherein_knowledge_label') . " AS l LEFT JOIN " . tablename('wherein_knowledge_relation') . " AS r ON r.label_id = l.label_id WHERE l.uniacid = :uniacid AND r.question_id = :question_id ", array(':uniacid' => $_W['uniacid'], ':question_id' => $question_item['question_id']), 'label_id');
            foreach ($label_list as $k => $v) {
                $label_list[$k]['is_selected'] = !empty($selected_label_list[$v['label_id']]) ? 1 : 0;
            }
        }
        //旧数据
        $question_item = isset($question_item) ? $question_item : array();

        if ($_W['isajax']) {
            //判断问题是否为空
            if (empty($_GPC['question'])) {
                $this->outjson(array('code' => 404, 'msg' => '请填写问题'));
            }
            //判断类别是否为空
            if (empty($_GPC['cat_id'])) {
                $this->outjson(array('code' => 404, 'msg' => '请选择类别'));
            }
            //判断答案是否为空
            if (empty($_GPC['answer'])) {
                $this->outjson(array('code' => 404, 'msg' => '请填写答案'));
            }

            $data = array();
            $data = array(
                'uniacid' => $_W['uniacid'],
                'cat_id' => $_GPC['cat_id'],
                'question' => trim($_GPC['question']),
                'answer' => $_GPC['answer'],
                'is_common' => $_GPC['is_common'],
                'similar_question' => !empty($_GPC['similar_question']) ? implode(QUESTION_IMPLODE, $_GPC['similar_question']) : ''
            );

            if (empty($_GPC['question_id'])) {

                //添加问题
                if (pdo_insert('wherein_knowledge_question', $data)) {
                    $q_id = pdo_insertid();

                    //如果标签不为空,插入关联表
                    if (!empty($_GPC['label_ids']) && is_array($_GPC['label_ids']) && !empty($q_id)) {
                        $i = 0;
                        $count_label_ids = count($_GPC['label_ids']);
                        $sql = "INSERT INTO " . tablename('wherein_knowledge_relation') . " (`uniacid`, `question_id`, `label_id`) VALUES ";
                        foreach ($_GPC['label_ids'] as $key => $value) {
                            if ($i < $count_label_ids) {
                                $sql .= "(";
                                $sql .= "'" . $_W['uniacid'] . "', '" . $q_id . "', '" . $value . "'";
                                $sql .= "),";
                            }
                            $i++;
                        }
                        $sql = rtrim($sql, ',');
                        if (!pdo_query($sql)) {
                            pdo_delete('wherein_knowledge_question', array('question_id' => $q_id));
                            $this->outjson(array('code' => 300, 'msg' => '添加问题失败'));
                        }
                    }
                    $this->outjson(array('code' => 200, 'msg' => '添加问题成功'));
                } else {
                    $this->outjson(array('code' => 300, 'msg' => '添加问题失败'));
                }
            } else {
                /* 修改问题 没有更改过数据条件: 更新返回结果为0+原标签数据与传数据相等 */

                $res = pdo_update('wherein_knowledge_question', $data, array('question_id' => $_GPC['question_id']));

                $selected_label_list_tmp = array();
                $_GPC['label_ids'] = empty($_GPC['label_ids']) ? array() : $_GPC['label_ids'];
                if (isset($selected_label_list)) {
                    $selected_label_list_tmp = return_array_value($selected_label_list, 'label_id');
                }

                if ($selected_label_list_tmp === $_GPC['label_ids']) {
                    if ($res == 0) {
                        $this->outjson(array('code' => 304, 'msg' => '您没有更改过数据'));
                    } else {
                        $this->outjson(array('code' => 200, 'msg' => '修改问题成功'));
                    }
                } else {
                    //查询原来问题对应的标签
                    $label_ids = pdo_getall('wherein_knowledge_relation', array('uniacid' => $_W['uniacid'], 'question_id' => $_GPC['question_id']), array('label_id'));
                    if (!empty($label_ids)) {
                        pdo_delete('wherein_knowledge_relation', array('question_id' => $_GPC['question_id']));
                    }

                    $i = 0;
                    $count_label_ids = count($_GPC['label_ids']);
                    if ($count_label_ids > 0) {
                        $sql = "INSERT INTO " . tablename('wherein_knowledge_relation') . " (`uniacid`, `question_id`, `label_id`) VALUES ";
                        foreach ($_GPC['label_ids'] as $key => $value) {
                            if ($i < $count_label_ids) {
                                $sql .= "(";
                                $sql .= "'" . $_W['uniacid'] . "', '" . $_GPC['question_id'] . "', '" . $value . "'";
                                $sql .= "),";
                            }
                            $i++;
                        }
                        $sql = rtrim($sql, ',');
                        if (!pdo_query($sql)) {
                            $this->outjson(array('code' => 0, 'msg' => '修改问题失败'));
                        }
                    }
                    $this->outjson(array('code' => 200, 'msg' => '修改问题成功'));
                }
            }
        }

        /* 用于判断编辑页面保存后跳转和返回键跳转 */
        $q_type = isset($_GPC['q_type']) && $_GPC['q_type'] == 2 ? 2 : 1;
        $back = $this->createWebUrl('knowledge', array('act' => ($q_type == 2 ? 'question' : 'index')));

        include $this->template('operate');
    }

    /*
     * 导入问题
     */
    public function excelQuestion() {
        global $_W,$_GPC;

        if (!is_writable(ATTACHMENT_ROOT)) {
            message(ATTACHMENT_ROOT . '目录不可写, 请授权', '', 'error');
        }
        //检测是upload和PHPExcel文件夹是否存在
        if (!is_dir(UPLOAD_EXCEL)) {
            if (!mkdir(UPLOAD_EXCEL, 0777, true)) {
                message('创建目录失败', 'referer', 'error');
            }
        }

        if (checksubmit()) {
            if (!empty($_FILES['phpexcel']['name'])) {

                $tmp_file = $_FILES['phpexcel']['tmp_name'];
                $file_types = explode (".", $_FILES['phpexcel']['name']);
                //取得文件后缀
                $file_type = $file_types[count($file_types)-1];
                /*判别是不是.xls文件，判别是不是excel文件*/
                if (!in_array(strtolower($file_type), array('xls', 'xlsx'))) {
                    message('不是Excel文件，重新上传', 'refresh', 'error');
                }
                if (get_upload_max_filesize_byte() < $_FILES['phpexcel']['size']) {
                    message('您上传的文件过大, 默认最大值为: ' . ini_get('upload_max_filesize'),  'refresh', 'error');
                }
                /*设置上传路径*/
                $save_path = UPLOAD_EXCEL;
                if (!is_dir($save_path)) {
                    message('没有找到可上传的路径', 'refresh', 'error');
                }
                /*以时间来命名上传的文件*/
                $str = 'q'.date('Ymdhis').mt_rand('100', '999');
                $file_name = $str . '.' . $file_type;
                //上传文件的路径
                $file_path = $save_path . $file_name;
                /*是否上传成功*/
                if (!copy($tmp_file, $file_path)) {
                    message('上传失败', 'refresh', 'error');
                }

                /* 处理 */
                require IA_ROOT . '/framework/library/phpexcel/PHPExcel.php';

                $objReader = PHPExcel_IOFactory::createReader('Excel5');
                $objExcel = $objReader->load($file_path);
                $sheet = $objExcel->getSheet(0);//读取第一个工作表
                $highestRow = $sheet->getHighestRow();//总行数
                if ($highestRow == 1) {
                    unlink($file_path);//删除导入的excel表
                    message('请在Excel表里添加需要导入的数据', 'refresh', 'error');
                } else if ($highestRow >= 1001) {
                    unlink($file_path);//删除导入的excel表
                    message('一次导入知识库条数最多为1000条', 'refresh', 'error');
                }

                $all_data = $objExcel->getActiveSheet()->toArray();
                $headerRow = $all_data[0];//表头
                unset($all_data[0]);

                $data = array();//正确的数据
                $err_list = array();//错误的数据
                $err_list[] = array(
                    $headerRow[0],
                    $headerRow[1],
                    $headerRow[2],
                    $headerRow[3],
                    $headerRow[4],
                    '错误原因',
                );
                //$success_import 导入成功数量 $fail_import 导入失败数量
                $success_import = $fail_import = 0;

                foreach ($all_data as $key => $value) {
                    if (!empty($value[0]) || !empty($value[1]) || !empty($value[2]) || !empty($value[3]) || !empty($value[4])) {
                        $error = array();

                        $question = $value[0];
                        if (empty($question)) {
                            $error[] = '问题不能为空';
                        }
                        if (utf8_strlen($question) > 50) {
                            $error[] = '问题字符数最多50个字';
                        }
                        $res_cate = pdo_getcolumn('wherein_knowledge_category', array('uniacid' => $_W['uniacid'], 'cat_name' => $value[2]), 'cat_id');
                        if (!empty($res_cate)) {
                            if (pdo_get('wherein_knowledge_question', array('uniacid' => $_W['uniacid'], 'question' => $question, 'cat_id' => $res_cate), array('question_id', 'cat_id'))) {
                                $error[] = '问题重复';
                            }
                        }

                        $answer = $value[1];
                        if (empty($answer)) {
                            $error[] = '答案不能为空';
                        }
                        if (utf8_strlen(htmlspecialchars($answer)) > 3000) {
                            $error[] = '答案字符数不能超过3000字';
                        }

                        $cat_name = $value[2];
                        if (empty($cat_name)) {
                            $error[] = '分类不能为空';
                        }

                        $label_name = $value[3];

                        $similar_question = $value[4];
                        $similar_question_list = array();
                        if (!empty($similar_question)) {
                            $similar_question_list = explode(';', $similar_question);
                            $s = 0;
                            foreach ($similar_question_list as $v) {
                                if (utf8_strlen($v) > 50) {
                                    $s = 1;
                                }
                            }
                            if (!empty($s)) {
                                $error[] = '每个相似问题字符数不能超过50个字';
                            }
                        }
                        /* 如果$error不为空, 则该条数据没有错 */
                        if (!empty($error)) {
                            $err_list[] = array(
                                $question,
                                $answer,
                                $cat_name,
                                $label_name,
                                $similar_question,
                                implode(QUESTION_IMPLODE, $error)
                            );
                        } else {
                            //判断每一行里的分类名在分类表里是否存在,存在则取id,不存在则新建分类
                            $cat_id = 0;
                            $res_cate = pdo_getcolumn('wherein_knowledge_category', array('uniacid' => $_W['uniacid'], 'cat_name' => $cat_name), 'cat_id');
                            if ($res_cate) {
                                $cat_id = $res_cate;
                            } else {
                                //如果不存在, 则新建
                                $cate_data = array(
                                    'uniacid' => $_W['uniacid'],
                                    'parent_id' => '0',//一级分类
                                    'cat_name' => trim($cat_name),
                                    'add_time' => $_W['timestamp'],
                                    'sort_order' => '0'
                                );
                                if (pdo_insert('wherein_knowledge_category', $cate_data)) {
                                    $cat_id = pdo_insertid();
                                }
                            }

                            //标签处理
                            $label_id_list = array();
                            if (!empty($label_name)) {
                                $label_list = explode(';', $label_name);
                                foreach ($label_list as $l) {
                                    $label_id = pdo_getcolumn('wherein_knowledge_label', array('uniacid' => $_W['uniacid'], 'label_name' => $l), 'label_id');
                                    if ($label_id) {
                                        $label_id_list[] = $label_id;
                                    } else {
                                        //如果不存在, 则新建
                                        $label_data = array(
                                            'uniacid' => $_W['uniacid'],
                                            'label_name' => trim($l),
                                            'author' => 'admin'
                                        );
                                        if (pdo_insert('wherein_knowledge_label', $label_data)) {
                                            $label_id_list[] = pdo_insertid();
                                        }
                                    }
                                }
                            }

                            $data[] = array(
                                'uniacid' => $_W['uniacid'],
                                'cat_id' => $cat_id,
                                'question' => htmlspecialchars($question),
                                'answer' => htmlspecialchars(strip_tags($answer)),
                                'similar_question' => !empty($similar_question_list) ? implode(QUESTION_IMPLODE, $similar_question_list) : '',
                                'label_list' => $label_id_list
                            );
                        }
                    }
                }
                //错误的条数 > 0 说明有错误数据
                $count_err = count($err_list) - 1;
                if ($count_err > 0) {
                    cache_clean('question_upload_list');
                    cache_write('question_upload_list', $err_list);
                }
                if (!empty($data)) {
                    foreach ($data as $key => $value) {
                        $question_data = array(
                            'uniacid' => $_W['uniacid'],
                            'cat_id' => $value['cat_id'],
                            'question' => $value['question'],
                            'answer' => $value['answer'],
                            'is_common' => 0,
                            'similar_question' => $value['similar_question'],
                            'author' => 'admin'
                        );
                        if (!pdo_insert('wherein_knowledge_question', $question_data)) {
                            message('写入数据库失败: '.$value['question'], 'refresh', 'error');
                        }
                        $question_id = pdo_insertid();
                        //标签的处理
                        if (!empty($value['label_list'])) {
                            $sql = "INSERT INTO " . tablename('wherein_knowledge_relation') . " (`uniacid`, `question_id`, `label_id`) VALUES ";
                            foreach ($value['label_list'] as $kv => $kl) {
                                $sql .= "(";
                                $sql .= "'" . $_W['uniacid'] . "', '" . $question_id . "', '" . $kl . "'";
                                $sql .= "),";
                            }
                            $sql = rtrim($sql, ',');
                            if (!pdo_query($sql)) {
                                pdo_delete('wherein_knowledge_question', array('question_id' => $question_id));
                                message('标签处理失败', 'refresh', 'error');
                            }
                        }
                        $success_import++;
                    }
                    message('导入成功', $this->createWebUrl('knowledge', array('act' => 'excelQuestion', 'step' => 3, 's' => $success_import, 'f' => $count_err)), 'success');
                } else {
                    message('没有可导入的数据', $this->createWebUrl('knowledge',array('act' => 'excelQuestion','step' => 3, 's' => 0, 'f' => $count_err)), 'error');
                }
            } else {
                message('请选择要上传的文件', 'refresh', 'error');
            }
        }
        include $this->template('excelQuestion');
    }

    /*
     * 下载标签excel文件
     */
    public function downloadLabel() {
        global $_GPC;
        $name = $_GPC['en_name'];
        $filename = KB_WEB_RELATIVE . 'Util/excel/' . $name . '.xls';
        $output_name = $name == 'question' ? '问题模板' : '标签模板';
        $filename = realpath($filename);
        $file_extension = strtolower(substr(strrchr($filename,"."),1));
        switch ($file_extension) {
            case "pdf": $ctype="application/pdf"; break;
            case "exe": $ctype="application/octet-stream"; break;
            case "zip": $ctype="application/zip"; break;
            case "doc": $ctype="application/msword"; break;
            case "xls": $ctype="application/vnd.ms-excel"; break;
            case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
            case "gif": $ctype="image/gif"; break;
            case "png": $ctype="image/png"; break;
            case "jpe": case "jpeg":
            case "jpg": $ctype="image/jpg"; break;
            default: $ctype="application/force-download";
        }
        if (!file_exists($filename)) {
            message('文件不存在', 'refresh', 'error');
        }
        $output_name=$output_name?:basename($filename);
        $output_name.='.'.$file_extension;

        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: private",false);
        header("Content-Type: $ctype");
        header("Content-Disposition: attachment; filename=\"".$output_name."\";");
        header("Content-Transfer-Encoding: binary");
        header('Content-Length: ' . filesize($filename));
        @readfile($filename) or die("File not found.");
    }

    /*
     * 导出失败问题
     */
    public function downFailFile() {
        $data = cache_load('question_upload_list');
        //对数据进行检验
        if(empty($data) || !is_array($data)){
            message('没有失败的数据可下载', 'referer', 'error');
        }
        $fileName = '导出失败数据表_' . date('Y_m_d', time()) . '.xls';
        //创建PHPExcel对象，注意，不能少了
        /* 处理 */
        require IA_ROOT . '/framework/library/phpexcel/PHPExcel.php';
        $objPHPExcel = new PHPExcel();
        $objProps = $objPHPExcel->getProperties();

        $objPHPExcel->getActiveSheet()->setTitle($fileName);

        $column = 1;
        $objActSheet = $objPHPExcel->getActiveSheet();
        foreach($data as $key => $rows){ //行写入
            $span = ord("A");
            foreach($rows as $keyName=>$value){// 列写入
                if($span<=90){
                    $j = chr($span);
                }else{
                    $j = chr($span-26);
                }
                $objActSheet->setCellValue($j.$column, $value);
                $span++;
            }
            $column++;
        }

        $fileName = iconv("utf-8", "gb2312", $fileName);
        //重命名表
        //设置活动单指数到第一个表,所以Excel打开这是第一个表
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output'); //文件通过浏览器下载
        exit;
    }

    /*
     * 常见问题列表
     */
    public function question() {
        global $_W, $_GPC;

        if ($_W['isajax']) {
            $where_sql = ' WHERE `uniacid`=:uniacid AND `is_common`=:is_common ';
            $where[':uniacid'] = $_W['uniacid'];
            $where[':is_common'] = 1;
            //符合问题的id集合
            $question_ids = array();

            /* 一级分类: 判断当前分类下是否有二级分类, 查询相关问题: 条件 一级分类+二级分类(如果有) */
            if (!empty($_GPC['cat_id'])) {
                //查询当下有没有子分类
                $child_list = pdo_getall('wherein_knowledge_category', array('uniacid' => $_W['uniacid'], 'parent_id' => $_GPC['cat_id']), array('cat_id'));
                $child_list = empty($child_list) ? array() : return_array_value($child_list, 'cat_id');
                array_push($child_list, $_GPC['cat_id']);
                $child_list_implode = implode(',', $child_list);
                //查询问题id
                $question_list = pdo_fetchall("SELECT question_id FROM " . tablename('wherein_knowledge_question') . " WHERE `uniacid` = :uniacid AND `cat_id` IN (".$child_list_implode.")", array(':uniacid' => $_W['uniacid']));
                if (!empty($question_list)) {
                    $question_list = return_array_value($question_list, 'question_id');
                    foreach ($question_list as $v) {
                        array_push($question_ids, $v);
                    }
                    unset($question_list);//销毁
                } else {
                    array_push($question_ids, '0');
                }
            }

            /* 搜索-问题 */
            if (!empty($_GPC['question'])) {
                //模糊查询
                $where_sql .= " AND (`question` LIKE :question OR `similar_question` LIKE :similar_question)";
                $where[':question'] = '%' . $_GPC['question'] . '%';
                $where[':similar_question'] = '%' . $_GPC['question'] . '%';
            }

            if (!empty($question_ids)) {
                $question_ids = array_unique($question_ids);
                $where_sql .= ' AND `question_id` IN (' . implode(',', $question_ids) . ')';
            }

            $total = pdo_fetchcolumn("SELECT COUNT(*) FROM " . tablename('wherein_knowledge_question') . $where_sql, $where);

            $list = pdo_fetchall("SELECT * FROM ".tablename('wherein_knowledge_question') . $where_sql . " ORDER BY " . $_GPC['sortName'] . " " . $_GPC['sortOrder'] . " LIMIT " . $_GPC['offset'] . ", " . $_GPC['limit'], $where);
            if (!empty($list)) {
                foreach ($list as $key => $value) {
                    //一级--二级
                    $cate_data = pdo_get('wherein_knowledge_category', array('uniacid' => $_W['uniacid'], 'cat_id' => $value['cat_id']), array('parent_id', 'cat_name'));
                    if (!empty($cate_data['parent_id'])) {
                        $cate_ = pdo_getcolumn('wherein_knowledge_category', array('uniacid' => $_W['uniacid'], 'cat_id' => $cate_data['parent_id']), 'cat_name');
                        $cate_data['cat_name'] = $cate_ . '－－' . $cate_data['cat_name'];
                    }
                    $list[$key]['cat_name'] = $cate_data['cat_name'];
                    $label_name_list = pdo_fetchall("SELECT l.label_name FROM " . tablename('wherein_knowledge_label') . " AS l LEFT JOIN " . tablename('wherein_knowledge_relation') . " AS r ON r.label_id = l.label_id WHERE l.uniacid=:uniacid AND r.question_id = :question_id", array(':uniacid' => $_W['uniacid'], ':question_id' => $value['question_id']));
                    if (!empty($label_name_list)) {
                        $label_name_list = return_array_value($label_name_list, 'label_name');
                        $label_name_list = implode('、', $label_name_list);
                    } else {
                        $label_name_list = '无';
                    }
                    $list[$key]['label_name'] = $label_name_list;
                    $list[$key]['answer_all'] = htmlspecialchars_decode($value['answer']);
                    $list[$key]['answer'] = strip_tags(htmlspecialchars_decode($value['answer']));
                    $list[$key]['index'] = ($key+1) + ($_GPC['limit'] * ($_GPC['offset']/$_GPC['limit']));
                }
            }

            $out['total'] = $total;
            $out['rows'] = $list;
            $this->outjson($out);
        }

        $act = 'question';
        include $this->template('common_question');
    }

    /*
     * 删除问题
     * 删除完问题后还得删除关联表里的数据
     */
    public function del() {
        global $_GPC;

        if (empty($_GPC['question_id']) || !is_array($_GPC['question_id'])) {
            $this->outjson(array('code' => 0, 'msg' => '没有选中要删除的问题'));
        }
        $str_question = implode(',', $_GPC['question_id']);
        if (pdo_query("DELETE FROM ".tablename('wherein_knowledge_question')." WHERE `question_id` IN (" . $str_question . ")")) {
            pdo_query("DELETE FROM ".tablename('wherein_knowledge_relation')." WHERE `question_id` IN (" . $str_question . ")");
            $out['code'] = 1;
            $out['msg'] = '删除问题成功';
        } else {
            $out['code'] = 0;
            $out['msg'] = '删除问题失败';
        }
        $this->outjson($out);
    }

    /*
     * 改变问题的常见状态
     */
    public function changeStatus() {
        global $_GPC, $_W;
        if (pdo_update('wherein_knowledge_question', array('is_common' => $_GPC['status']), array('uniacid' => $_W['uniacid'], 'question_id' => $_GPC['question_id']))) {
            $this->outjson(array('code' => 200, 'msg' => $_GPC['status'] == 1 ? '设为常见问题成功' : '取消常见问题成功'));
        } else {
            $this->outjson(array('code' => 304, 'msg' => '改变状态失败,请检查原因'));
        }
    }


    /*
     * 检测当前分类名是否存在
     * @param string $name 分类名
     * $param int $is_parent 是否顶级分类 0是 1否
     */
    public function checkCateName($name, $is_parent = 0) {
        global $_W;
        if (empty($name)) {
            return array('code' => 0, 'msg' => '参数不全');
        }
        $sql = " AND `cat_name` = :cat_name ";
        if ($is_parent == 0) {
            $sql .= " AND parent_id = 0 ";
        } else if ($is_parent == 1) {
            $sql .= " AND parent_id <> 0 ";
        } else {
            return array('code' => 0, 'msg' => '参数错误');
        }
        $res = pdo_fetch("SELECT `cat_id` FROM " . tablename('wherein_knowledge_category') . " WHERE `uniacid` = :uniacid" . $sql, array(':uniacid' => $_W['uniacid'], ':cat_name' => trim($name)));
        return $res ? array('code' => 0, 'msg' => '该类别已存在') : array('code' => 1);
    }

    /*
     * 获取分类管理数据
     */
    public function getCateList() {
        global $_W;
        //分类管理数据 一级分类和二级分类
        $category_list = $category_child_list = array();
        $category_list = pdo_getall('wherein_knowledge_category', array('uniacid' => $_W['uniacid'], 'parent_id' => '0'), array('cat_id', 'cat_name', 'sort_order'), '', array('sort_order DESC'));
        $count = count($category_list);
        foreach ($category_list as $k => $v) {
            $child_list = pdo_getall('wherein_knowledge_category', array('uniacid' => $_W['uniacid'], 'parent_id' => $v['cat_id']), array('cat_id', 'cat_name', 'sort_order'), '', array('sort_order DESC'));
            $category_list[$k] = array(
                'cat_id' => $v['cat_id'],
                'cat_name' => $v['cat_name'],
                'sort_order' => $v['sort_order'],
                'child_list' => $child_list,
                'count_parent_list' => $count,
                'count_child_list' => count($child_list)
            );
            unset($child_list);
        }
        $out = empty($category_list) ? array('code' => 400, 'category_list' => array()) : array('code' => 200, 'category_list' => $category_list);
        $this->outjson($out);
    }

}